package com.qipay.sp.excutor.qmpay;

import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.JsonUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class QmpayWxTradeQueryExcutor extends AbstractExcutor {

    private final static String KEY_NAME="key";
    private final static String CONFIG_KEY_NAME="key_query";
    private final static String CONFIG_MCHID_NAME="mch_id";
    private final static String SIGN_NAME="sign";
    private final static String API_PARAM_TRX_TYPE="trxType";
    private final static String API_PARAM_MERCHANT_NO="merchantNo";
    private final static String API_PARAM_ORDER_NUM="orderNum";
    private final static String API_URL="http://47.94.167.186:8085/qmpaytrx/online/query";

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.WX_TRADE_QUERY;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put(QmpayWxTradeQueryExcutor.API_PARAM_ORDER_NUM, order.getTradeNo());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {

        Object key = getVal(spconfig, QmpayWxTradeQueryExcutor.CONFIG_KEY_NAME);
        Object merchantNo = getVal(spconfig, QmpayWxTradeQueryExcutor.CONFIG_MCHID_NAME);
        Object orderNum = getVal(params, QmpayWxTradeQueryExcutor.API_PARAM_ORDER_NUM);
        Object trxType = getVal(params, QmpayWxTradeQueryExcutor.API_PARAM_TRX_TYPE);

        String signData = trxType.toString() + merchantNo.toString() + orderNum.toString() + key.toString();
        String sign = DigestUtils.md5Hex(signData);
        logger.info("签名串：{}，签名：{}",signData,sign);

        params.put(QmpayWxTradeQueryExcutor.API_PARAM_MERCHANT_NO, merchantNo);
        params.put(QmpayWxTradeQueryExcutor.SIGN_NAME, sign);

        String result = sendPostByKeyValue(params, QmpayWxTradeQueryExcutor.API_URL);
        if(StringUtils.isBlank(result)){
            throw new Exception("请求qmpay的查询接口失败");
        }
        Map<String, Object> responseMap = JsonUtils.toMap(result);
        Map<String, Object> resultMap = new HashMap<>();

        if(responseMap == null || !responseMap.containsKey("retCode") ||
                responseMap.get("retCode") == null)
        {
            logger.error("请求qmpay的查询接口失败:" + result);
            return null;
        }
//        if(!isResponseValid(responseMap, key.toString(), QmpayTradeQueryExcutor.SIGN_NAME,
//                QmpayTradeQueryExcutor.KEY_NAME)) {
//            logger.error("请求qmpay的查询返回值的签名失败:" + result);
//            return null;
//        }

        if(!"0000".equalsIgnoreCase(responseMap.get("retCode").toString()))
        {
            logger.error("请求qmpay的查询接口业务执行失败:" + result);
            resultMap.put("result_code", "1");
            resultMap.put("err_code", responseMap.get("retCode"));
            resultMap.put("err_msg", responseMap.get("retMsg"));
            return resultMap;
        }
        resultMap.put("result_code", "0");

        resultMap.put("trade_state", "SUCCESS".equals(responseMap.get("r8_orderStatus"))? "SUCCESS":"NOTPAY");
        resultMap.put("trade_no", responseMap.get("r2_orderNumber"));
        resultMap.put("out_transaction_id", responseMap.get("r2_orderNumber"));
//        resultMap.put("total_fee", responseMap.get("r3_amount"));
        resultMap.put("time_end", responseMap.get("r7_completeDate"));
        return resultMap;
    }
}
